/*
 * @Description:
 * @Author: Dxcr
 * @Date: 2025-03-06 09:59:35
 * @LastEditTime: 2025-04-03 15:57:17
 * @LastEditors: Dxcr
 */
import router from "./router";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/auth";
import { isHttp } from "@/utils/validate";
import useUserStore from "@/stores/user";
import usePermissionStore from "@/stores/permission";

const whiteList = ["/index","/login", "/register"];
router.beforeEach((to, from, next) => {
  // 无接口暂时注释
  if (getToken()) {
    /* has token*/
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      if (useUserStore().roles.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        useUserStore()
          .getInfo()
          .then(() => {
            usePermissionStore()
              .generateRoutes()
              .then((accessRoutes) => {
                // 根据roles权限生成可访问的路由表
                accessRoutes.forEach((route) => {
                  if (!isHttp(route.path)) {
                    router.addRoute(route); // 动态添加可访问路由表
                  }
                });
                next({ ...to, replace: true }); // hack方法 确保addRoutes已完成
              });
          })
          .catch((err) => {
            console.log(err);
            useUserStore()
              .logOut()
              .then(() => {
                ElMessage.error(err);
                next({ path: "/" });
              });
          });
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
    }
  }
});

router.afterEach(() => {});
